package com.simple.modules.sys.controller;

import com.simple.modules.sys.entity.SysUserEntity;
import com.simple.modules.sys.entity.SysUserRoleEntity;
import com.simple.modules.sys.service.SysUserRoleService;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Controller公共组件
 */
@Component
public abstract class AbstractController {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SysUserRoleService sysUserRoleService;

    protected SysUserEntity getUser() {
        SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        List<SysUserRoleEntity> userRoleList = sysUserRoleService.getByUserId(user.getUserId());
        List<Integer> roleIdList = userRoleList.stream().map(SysUserRoleEntity::getRoleId).collect(Collectors.toList());
        user.setRoleIdList(roleIdList);
        return user;
    }

    protected Long getUserId() {
        return getUser().getUserId();
    }

    //todo 隐性判断roleId是管理员
    public static List<Integer> ADMIN_ID_LIST = Arrays.asList(1);

    protected Boolean judeUserIsAdmin() {
        SysUserEntity user = getUser();
        List<Integer> roleIdList = user.getRoleIdList();
        if (roleIdList.size() == 0) {
            return false;
        }
        for (Integer roleId : roleIdList) {
            if (ADMIN_ID_LIST.contains(roleId)) {
                return true;
            }
        }
        return true;
    }
}
